import 'dart:async';

import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:yysk_app/model/pay_model/bank_card_list_model.dart';
import 'package:yysk_app/model/pay_model/payment_query_withdraw_rule_model.dart';
import 'package:yysk_app/model/pay_model/user_list_pay_certification_model.dart';
import 'package:yysk_app/model/pay_model/user_pay_zhifu_url.dart';
import 'package:yysk_app/model/pay_model/user_register_query_model.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/enterprise_auth_zhifu/my_webview_zhifu_user_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/select_bank/select_bank_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/wallet/wallet_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/utils/transaction_password_page.dart';

class BankCardInfo {
  final String bankName;
  final String tailNo;
  BankCardInfo(this.bankName, this.tailNo);
}

class WithdrawController extends GetxController {
  // var availableAmount = 0.0.obs;
  var selectedBank = Rxn<BankCardInfo>();
  var amountController = TextEditingController();
  var canWithdraw = false.obs;
  final listPayCertification = RxList<UserListPayCertificationModel?>([]);
  final ScrollController scrollController = ScrollController();
  final detail = '0.00'.obs; //可提现
  var type = '1'.obs; //1个人，2企业,3个体工商户
  var plat = 'USER'.obs;
  var channel = 'DIN_PAY'.obs;
  final detailInfo = Rx<PaymentQueryWithdrawRuleModel?>(null);
  var payCards = RxList<BankCardListModel>();
  final selsectInfo = Rx<BankCardListModel?>(null);
  final getPrice = '0'.obs;
  final feeAmount = '0'.obs;
  final isRefresh = true.obs;
  Timer? timer;
  @override
  void onInit() {
    super.onInit();
    type.value = Get.parameters['type'] ?? Get.arguments['type'];
    channel.value = Get.parameters['channel'] ?? Get.arguments['channel'];
    // amountController.addListener(_onAmountChanged);
    amountController.text = '';
    getInfo();
    getListPay();
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
  }

  void selectBank() async {
    // if(type.value!='1'){
    //   return;
    // }
    isRefresh.value = false;
    showSelectBankDialog(context: Get.context!).then((result) {
      isRefresh.value = true;
    });

    // final result = await Get.toNamed(SelectBankPage.path);
    // if (result is BankCardInfo) {
    //   selectedBank.value = result;
    //   _onAmountChanged();
    // }
  }

  void withdrawAll() {
    amountController.text = double.parse(
      detailInfo.value!.balance ?? '0',
    ).toStringAsFixed(2);
    getManei();
  }

  //获取提现剩余金钱
  void confirmWithdraw() {
    // 提现逻辑
    Get.snackbar('提现', '提现申请已提交');
  }

  Future getInfo() async {
    await http.netFetch<PaymentQueryWithdrawRuleModel>(
      PayUrl.queryWithdrawRule,
      params: {'channel': channel.value, "plat": plat.value},
      success: (res) {
        if (res.code == 200) {
          detailInfo.value = res.data;
        }
      },
    );
  }

  Future getListPay() async {
    await http.netFetch<List<UserListPayCertificationModel>>(
      PayUrl.listPayCertification,
      method: Method.post,
      params: {},
      success: (res) {
        listPayCertification.value = res.data ?? [];
      },
    );
  }

  //去实名认证
  toOpenWallet() async {
    await showConfirmDialog(
      context: Get.context!,
      message: '请先完成实名认证',
      messages: [],
      fontSize: 16,
      actions: [
        ActionModel(
          label: '取消',
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
          onPressed: () {},
        ),
        ActionModel(
          label: '立即认证',
          onPressed: () {
            Get.toNamed(SettingRealNameAuthPage.path);
          },
        ),
      ],
    );
  }

  //是否开通交易密码
  Future<dynamic> isSetPayPassword() async {
    try {
      showConfirmDialog(
        context: Get.context!,
        message: '请先设置交易密码',
        messages: [],
        fontSize: 16,
        actions: [
          ActionModel(label: '取消', onPressed: () {}),
          ActionModel(
            label: '前往设置',
            onPressed: () {
              Get.toNamed(ChangeExchangePassword.path);
            },
          ),
        ],
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  //是否开通钱包
  Future<dynamic> isOpenWallet({bool isAddBank = false}) async {
    try {
      await http.netFetch<UserRegisterQueryModel>(
        PayUrl.registerQuery,
        method: Method.post,
        params: {'plat': 'USER', 'channel': channel.value},
        success: (result) {
          if (result.code == 200 && result.data?.status == true) {
            sub();
          } else {
            showConfirmDialog(
              context: Get.context!,
              message: '请先开通钱包',
              messages: ['开通后请前往藏品待支付订单中支付'],
              actions: [
                ActionModel(
                  label: '取消',
                  onPressed: () {},
                  colorStart: AppColors.backgroundColorGreyF8,
                  colorEnd: AppColors.backgroundColorGreyF8,
                  fontColor: AppColors.fontColor,
                ),
                ActionModel(
                  label: '前往开通',
                  onPressed: () {
                    Get.toNamed(WalletPage.path);
                  },
                ),
              ],
            );
          }
        },
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  //提现&&校验
  Future sub() async {
    TransactionPasswordDialog.show(
      Get.context!,
      onCompleted: (password) async {
        http.netFetch<dynamic>(
          ProductApi.verifySecurityPassword,
          params: {'payPassword': password},
          method: Method.post,
          success: (result) async {
            if (result.code == 200) {
              await http.netFetch<dynamic>(
                PayUrl.withdraw,
                params: {
                  'payAmt': amountController.text,
                  'channel': channel.value,
                  "plat": plat.value,
                },
                success: (res) {
                  if (res.code == 200) {
                    amountController.text = '';
                    showToast('提现成功');
                    getInfo();
                    getListPay();
                  }
                },
              );
            }
          },
        );
      },
      onCancel: () {
        // 取消回调（可选）
      },
    );
  }

  /// 验证金额格式的方法 calcWithdrawAmount
  void validateAmount(String value) {
    // 定义正则表达式（与上面一致）
    final regex = RegExp(
      r'^[1-9]\d*|0?\d+(?:,\d{3})*(?:\.\d{1,2})?$',
      caseSensitive: false,
    );

    // 检查是否匹配正则
    if (!regex.hasMatch(value.trim())) {
      // 若不匹配，更新错误提示
      showToast('请输入有效的金额');
    } else {
      showToast('有效');
    }
  }

  Future getManei() async {
    if (amountController.text.isEmpty) {
      return;
    }
    await http.netFetch<dynamic>(
      PayUrl.calcWithdrawAmount,
      params: {
        'channel': channel.value,
        "plat": plat.value,
        'amount': amountController.text,
      },
      success: (res) {
        if (res.code == 200) {
          getPrice.value = res.data['amount'];
          feeAmount.value = res.data['feeAmount'];
        }
      },
    );
  }
}
